﻿using System.Windows;
using AzureTracer.Resources;
using AzureTracer.ViewModels;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using System.Collections.Generic;
using Serialization;
using Microsoft.Phone.Tasks;
using System;

namespace AzureTracer.Views
{
    public partial class SettingsPage : PhoneApplicationPage
    {
        bool _isNewPageInstance = false;

        public SettingsPage()
        {
            InitializeComponent();
            Loaded += OnLoaded;
            Unloaded += OnUnloaded;            
            _isNewPageInstance = true;

        }
        void OnShowMessage(string message)
        {
            if (MessageBox.Show(message, labels.SignOut, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                Messenger.Default.Send<bool>(true, SettingsViewModel.CONFIRMDIALOG_MESSAGE);
        }

        void OnLoaded(object sender, RoutedEventArgs e)
        {
            ApplicationBar.MatchOverriddenTheme();
            Messenger.Default.Register<string>(this, SettingsViewModel.OKCANCELDIALOG_MESSAGE, OnShowMessage);
        }

        void OnUnloaded(object sender, RoutedEventArgs e)
        {
            Messenger.Default.Unregister<string>(this, SettingsViewModel.OKCANCELDIALOG_MESSAGE);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode != NavigationMode.Back)
                State["ViewModel"] = SilverlightSerializer.Serialize(this.DataContext);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (!_isNewPageInstance) return;

           if (State.Count != 0)
                DataContext = SilverlightSerializer.Deserialize(State["ViewModel"] as byte[]);            
            State.Clear();

            _isNewPageInstance = false;
        }

        private void AboutMeButton_Click(object sender, RoutedEventArgs e)
        {
            WebBrowserTask navegator = new WebBrowserTask() { Uri = new Uri("http://albertofraj.wordpress.com/") };
            navegator.Show();
        }
    }
}